package com.platform.destiny.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.platform.destiny.common.Constant;
import com.platform.destiny.dto.UserDto;
import com.platform.destiny.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt filter
 */
@Slf4j
public class JwtAuthFilter extends BasicAuthenticationFilter {


    public JwtAuthFilter(AuthenticationManager manager) {
        super(manager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        String token = request.getHeader(Constant.token_name);
        if (StrUtil.isBlank(token)) {
            chain.doFilter(request, response);
            return;
        }

        UserDto dto = JwtUtils.parseToken(token);
        if (ObjectUtil.isNotEmpty(dto)) {
            // 	principal 主体 身份实体信息，用户名 邮箱等唯一标识
            //	credentials 凭证 密码 证书 凭据 令牌
            UsernamePasswordAuthenticationToken tk = new UsernamePasswordAuthenticationToken(dto, dto.getPassword(), dto.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(tk);
            log.info("jwt filter {} ", tk.getPrincipal());
        }
        log.info("jwt auth filter!");
        chain.doFilter(request, response);

    }


}
